<template>
	<view class="container p-bottom" v-if="detail.order_goods_id">
		<form @submit="onSubmit" report-submit>
			<!-- 商品详情 -->
			<form @submit="onGoodsDetail" :report-submit="true">
				<button class="btn-normal" formType="submit" :data-id="detail.goods_id">
					<view class="goods-detail b-f dis-flex flex-dir-row">
						<view class="left"><image class="goods-image" :src="detail.image.file_path"></image></view>
						<view class="right dis-flex flex-box flex-dir-column flex-x-around">
							<view class="goods-name">
								<text class="twolist-hidden">{{ detail.goods_name }}</text>
							</view>
							<view class="dis-flex col-9 f-24">
								<view class="flex-box">{{ detail.goods_attr }}</view>
								<text class="t-r">×{{ detail.total_num }}</text>
							</view>
						</view>
					</view>
				</button>
			</form>

			<!-- 服务类型 -->
			<view class="row-service b-f m-top20">
				<view class="row-title">{{ $t('page_refund_apply.Service_type') }}</view>
				<form @submit="onSwitchService" :report-submit="true">
					<view class="service-switch dis-flex">
						<button class="btn-normal" formType="submit" data-type="10">
							<view :class="'switch-item ' + (serviceType == 10 ? 'active' : '')">{{ $t('page_refund_apply.Refund_returned_goods') }}</view>
						</button>
						<button class="btn-normal dis-flex" formType="submit" data-type="20">
							<view :class="'switch-item ' + (serviceType == 20 ? 'active' : '')">{{ $t('page_refund_apply.replacement') }}</view>
						</button>
					</view>
				</form>
			</view>

			<!-- 申请原因 -->
			<view class="row-textarea b-f m-top20">
				<view class="row-title">{{ $t('page_refund_apply.Reason_application') }}</view>
				<view class="content"><textarea name="content" maxlength="2000" :placeholder="$t('page_refund_apply.placeholder')" placeholderStyle="color:#ccc"></textarea></view>
			</view>

			<!-- 退款金额 -->
			<view v-if="serviceType == 10" class="row-money b-f m-top20 dis-flex">
				<view class="row-title">{{ $t('page_refund_apply.Refund_amount') }}</view>
				<view class="money col-m">{{ price_mode.unit }}{{ detail.total_pay_price }}</view>
			</view>

			<!-- 上传凭证 -->
			<view class="row-voucher b-f m-top20">
				<view class="row-title">{{ $t('page_refund_apply.upload_certificate') }}</view>
				<view class="image-list">
					<!-- 图片列表 -->
					<view class="image-preview" v-for="(imagePath, imageIndex) in imageList" :key="imageIndex">
						<text class="image-delete iconfont icon-shanchu" @tap.stop.prevent="deleteImage" :data-index="index" :data-image-index="imageIndex"></text>

						<image mode="aspectFill" :src="imagePath"></image>
					</view>
					<!-- 上传图片 -->
					<form v-if="imageList.length < 6" @submit="chooseImage" :report-submit="true">
						<button class="btn-normal" formType="submit">
							<view class="image-picker dis-flex flex-dir-column flex-x-center flex-y-center">
								<text class="choose__icon iconfont icon-tubiao_xiangji"></text>
								<text class="choose__text">{{ $t('page_refund_apply.Upload_pictures') }}</text>
							</view>
						</button>
					</form>
				</view>
			</view>

			<view class="flow-fixed-footer b-f">
				<button class="btn-normal" formType="submit">
					<view class="flow-btn f-32">{{ $t('page_refund_apply.Confirm_submission') }}</view>
				</button>
			</view>
		</form>
	</view>
</template>

<script>
const app = getApp();
export default {
	data() {
		return {
			// 订单商品id
			order_goods_id: null,
			price_mode: uni.getStorageSync('price_mode'),
			// 订单商品详情
			detail: {
				order_goods_id: '',
				goods_id: '',

				image: {
					file_path: ''
				},

				goods_name: '',
				goods_attr: '',
				total_num: '',
				total_pay_price: ''
			},

			// 图片列表
			imageList: [],

			// 服务类型
			serviceType: 10,

			imageIndex: 0,
			imagePath: ''
		};
	},
	/**
	 * 生命周期函数--监听页面加载
	 */ onLoad: function(options) {
		// 记录页面参数
		this.order_goods_id = options.order_goods_id; // 获取订单商品详情

		this.getGoodsDetail();
	},
	methods: {
		disable: false,

		/**
		 * 获取订单商品详情
		 */
		getGoodsDetail: function() {
			let that = this;

			app.globalData._get(
				'user.refund/apply',
				{
					order_goods_id: this.order_goods_id
				},
				function(result) {
					that.setData(result.data);
				}
			);
		},

		/**
		 * 切换标签
		 */
		onSwitchService: function(e) {
			// 记录formId
			app.globalData.saveFormId(e.detail.formId);
			this.serviceType= e.detail.target.dataset.type
		},

		/**
		 * 跳转商品详情
		 */
		onGoodsDetail: function(e) {
			// 记录formId
			app.globalData.saveFormId(e.detail.formId);
			uni.navigateTo({
				url: '../../../goods/index?goods_id=' + e.detail.target.dataset.id
			});
		},

		/**
		 * 选择图片
		 */
		chooseImage: function(e) {
			let that = this;
			let index = e.currentTarget.dataset.index;
			let imageList = that.imageList; // 记录formId
			app.globalData.saveFormId(e.detail.formId); // 选择图片

			uni.chooseImage({
				count: 6 - imageList.length,
				sizeType: ['original', 'compressed'],
				// 可以指定是原图还是压缩图，默认二者都有
				sourceType: ['album', 'camera'],
				// 可以指定来源是相册还是相机，默认二者都有
				success: function(res) {
					that.imageList= imageList.concat(res.tempFilePaths)
				}
			});
		},

		/**
		 * 删除图片
		 */
		deleteImage: function(e) {
			let dataset = e.currentTarget.dataset;
			let imageList = this.imageList;
			imageList.splice(dataset.imageIndex, 1);
			this.imageList = imageList
		},

		/**
		 * 表单提交
		 */
		onSubmit: function(e) {
			let that = this;

			if (!e.detail.value.content) {
				app.globalData.showError('申请原因不能为空');
				return false;
			} // 判断是否重复提交

			if (that.disable === true) {
				return false;
			} // 表单提交按钮设为禁用 (防止重复提交)

			that.disable = true;
			uni.showLoading({
				title: '正在处理...',
				mask: true
			}); // form参数

			let postParams = {
				order_goods_id: that.order_goods_id,
				type: that.serviceType,
				content: e.detail.value.content
			}; // form提交执行函数

			let fromPostCall = function(params) {
				console.log('fromPostCall');

				app.globalData._post_form(
					'user.refund/apply',
					params,
					function(result) {
						if (result.code === 1) {
							app.globalData.showSuccess(result.msg, function() {
								// 跳转售后管理页面
								uni.navigateTo({
									url: '../index'
								});
							});
						} else {
							app.globalData.showError(result.msg);
						}
					},
					false,
					function() {
						uni.hideLoading();
						that.disable = false;
					}
				);
			}; // 统计图片数量

			let imagesLength = that.imageList.length; // 判断是否需要上传图片

			if (imagesLength > 0) {
				that.uploadFile(imagesLength, fromPostCall, postParams);
			} else {
				fromPostCall(postParams);
			}
		},

		/**
		 * 上传图片
		 */
		uploadFile: function(imagesLength, callBack, formData) {
			let uploaded = []; // 文件上传

			let i = 0;
			this.imageList.forEach(function(filePath, fileKey) {
				uni.uploadFile({
					url: app.globalData.api_root + 'upload/image',
					filePath: filePath,
					name: 'iFile',
					formData: {
						wxapp_id: app.globalData.getWxappId(),
						token: uni.getStorageSync('token')
					},
					success: function(res) {
						let result = typeof res.data === 'object' ? res.data : JSON.parse(res.data);

						if (result.code === 1) {
							uploaded[fileKey] = result.data.file_id;
						}
					},
					complete: function() {
						i++;

						if (imagesLength === i) {
							// 所有文件上传完成
							console.log('upload complete');
							formData['images'] = uploaded; // 执行回调函数

							if (callBack) {
								callBack(formData);
							}
						}
					}
				});
			});
		}
	}
};
</script>
<style>
@import './apply.css';
</style>
